<script lang="ts" setup>
interface SourceItemType {
  v: string
  r: string[]
  vba: string
}
defineOptions({ name: 'AppRebateContent' })

const appStore = useAppStore()
const { currentGlobalCurrency, isLogin } = storeToRefs(appStore)

const { isMobile } = storeToRefs(useWindowStore())
const { rebateTypeArr, customPlatformName, customFormat } = useRebateData()
const { isZeroShowOther } = useVipInfo() // 检查是否为各种0值
// const { openRebateDetailDialog } = useDialogRebatedetail()

/** 获取返水配置 */
const { runAsync: runAsyncRebateAutomatic, data: rebateAutomatic } = useRequest(ApiMemberRebateAutomatic)
/** VIP返水模式 */
const { runAsync: runVipRebateVIPConfig } = useRequest(ApiMemberVipRebateVIPConfig)
/** 梯级返水数据 */
const tieredRebateValidBetData = ref()
/** 当前类型总的可领取金额 */
const tieredTotalRebate = ref('0')
/** 梯级返水模式  不是统一场馆 */
const { runAsync: runMemberTieredRebateValidBet } = useRequest(ApiMemberTieredRebateValidBet, {
  onSuccess: (data) => {
    tieredTotalRebate.value = '0'
    if (!data) {
      return tieredRebateValidBetData.value = data
    }
    else {
      tieredRebateValidBetData.value = data.map((item) => {
        const rebate_amount = customFormat(item.rebate_amount, 1)
        tieredTotalRebate.value = customFormat(add(+rebate_amount, +tieredTotalRebate.value), 1)
        const less_valid_bet_amount = customFormat(item.less_valid_bet_amount, 1)
        const valid_bet_amount = customFormat(item.valid_bet_amount, 1)
        const rate = customFormat(item.rate, 3)
        const next_rate = customFormat(item.next_rate, 3)
        const progressBar = `${+item.valid_bet_amount / +add(+item.less_valid_bet_amount, +item.valid_bet_amount) * 100}`
        return { ...item, rebate_amount, less_valid_bet_amount, valid_bet_amount, progressBar, rate, next_rate }
      })
    }
  },
})
/** 梯级返水模式  统一场馆 */
const { runAsync: runMemberTieredRebateSumValidBet } = useRequest(ApiMemberTieredRebateSumValidBet, {
  onSuccess: (data) => {
    tieredTotalRebate.value = '0'
    if (!data) {
      return tieredRebateValidBetData.value = data
    }
    else {
      tieredRebateValidBetData.value = data.map((item) => {
        const rebate_amount = customFormat(item.rebate_amount, 1)
        tieredTotalRebate.value = customFormat(add(+rebate_amount, +tieredTotalRebate.value), 1)
        const less_valid_bet_amount = customFormat(item.less_valid_bet_amount, 1)
        const valid_bet_amount = customFormat(item.valid_bet_amount, 1)
        const rate = customFormat(item.rate, 3)
        const next_rate = customFormat(item.next_rate, 3)
        const progressBar = `${+item.valid_bet_amount / +add(+item.less_valid_bet_amount, +item.valid_bet_amount) * 100}`
        // 场馆图标
        const game_type_icon = rebateTypeArr.find(a => item.game_type === a.value)?.icon
        return { ...item, rebate_amount, less_valid_bet_amount, valid_bet_amount, progressBar, rate, next_rate, game_type_icon }
      })
    }
  },
})
const APILoading = ref(false)
/** 当前类型的值 */
const tab = ref('')
const tabList = ref<typeof rebateTypeArr>([])
const columns = ref<Column[]>([])
const rebateConfig = ref<{ [t: string]: string }[]>([])
const currentGlobalCurrency2 = computed(() => {
  if (isLogin.value) {
    return currentGlobalCurrency.value
  }
  else {
    return languageConfig[getCurrentLanguageForFrontend()]?.currency
      ?? (getCurrentLanguageForFrontend() === 'pt-BR' ? 'BRL' : 'USDT')
  }
})
const globalCurrencyCode = computed(() => currencyConfig[currentGlobalCurrency2.value]?.cur)

/** 是否梯级模式 */
const isTiered = computed(() => {
  if (rebateAutomatic.value)
    return +rebateAutomatic.value.mode === 2
  return false
})
/** 是否梯级只展示一种货币 */
const isUnified = computed(() => {
  if (rebateAutomatic.value)
    return +rebateAutomatic.value.unified === 1
  return false
})
/** 是否梯级展示统一场馆 */
const isUnifiedSum = computed(() => {
  if (rebateAutomatic.value)
    return +rebateAutomatic.value.unified_sum === 1
  return false
})

/** 设置VIP表格头 */
function setColumn(name: string[]) {
  columns.value = name.map((item, index) => {
    const title = customPlatformName(item)
    return { title, dataIndex: `rate${index}`, align: 'center', color: 'var(--tg-table-text-color)' }
  })
  columns.value.unshift({
    title: `${$t('vip_club_rebate_table_header_vip_grade', { data: 'VIP' })}`,
    dataIndex: 'v',
    align: 'center',
    slot: 'level',
    skeWidth: '32px',
  })
}
/** 设置VIP表格的值 */
function setSource(data: { v: string, r: string[] }[]) {
  rebateConfig.value = data.map((item) => {
    const { v, r, vba } = item as SourceItemType
    const obj: { [t: string]: string } = {}
    obj.vba = isZeroShowOther(vba) ? vba : application.formatNumDecimal(vba, 2)
    obj.v = v
    for (const i in r)
      obj[`rate${i}`] = isZeroShowOther(r[i]) ? '-' : `${application.formatNumDecimal(r[i], 2, 1)}%`
    return obj
  })
}
/** 组装VIP所有数据 */
function setAllData(data: Record<string, any>) {
  const { data: _data, name } = data
  setColumn(name)
  setSource(_data)
}
/** 初始化数据 */
async function getData(showLoading = true) {
  if (showLoading)
    APILoading.value = true
  try {
    const currency_id = supportedCur.includes(globalCurrencyCode.value) ? globalCurrencyCode.value : '706'
    const { gts, mode, unified_sum } = await runAsyncRebateAutomatic(currency_id)
    // 如果是统一场馆不用tabs
    if (mode === '2' && unified_sum === '1') {
      await runMemberTieredRebateSumValidBet({ currency_id: globalCurrencyCode.value })
    }
    else {
      tabList.value = gts.split(',').map((id: string) => rebateTypeArr.find(a => id === a.value)).filter(Boolean) as typeof rebateTypeArr
      if (tab.value) {
        const res = tabList.value.find(item => tab.value === item.value)
        if (!res)
          tab.value = tabList.value[0].value
      }
      else {
        tab.value = tabList.value[0].value
      }
      if (!tab.value)
        return
      if (mode === '1') {
        const data = await runVipRebateVIPConfig({ game_type: tab.value, cur: '' })
        if (data)
          setAllData(data)
      }
      else if (mode === '2') {
        await runMemberTieredRebateValidBet({ game_type: tab.value, currency_id: globalCurrencyCode.value })
      }
    }
    APILoading.value = false
  }
  catch (error) {
    console.log(error)
    APILoading.value = false
  }
}

function toDetailPage(name: string, game_type: string) {
    i18nNavigateTo(`/rebate-center/detail?value=${tab.value || game_type}&name=${encodeURIComponent(name)}&isUnified=${isUnified.value}&isUnifiedSum=${isUnifiedSum.value}`)
}

watch([currentGlobalCurrency, tab], ([nvl1], [ovl1, ovl2]) => {
  APILoading.value = true
  if (ovl2 && !isTiered.value) {
    runVipRebateVIPConfig({
      game_type: tab.value,
      cur: '',
    }).then((data) => {
      const { data: _data, name } = data
      setColumn(name)
      setSource(_data)
    }).finally(() => {
      APILoading.value = false
    })
  }
  else if (nvl1 !== ovl1 && isTiered.value) {
    getData()
  }
  else if (ovl2 && isTiered.value) {
    runMemberTieredRebateValidBet({ game_type: tab.value, currency_id: globalCurrencyCode.value }).finally(() => {
      APILoading.value = false
    })
  }
})

watch(isLogin, () => isTiered.value && getData())

onMounted(() => {
  console.log('🚸🚸🚸 ~ onMounted ~ 返水页面挂载了:')
  appEventBus.on(EventBusNames.GET_TIIMEREBATE_SUCCESS, () => {
    isTiered.value && getData()
  })
})
onActivated(() => {
  // 活动首页会使用缓存这个页面
  isTiered.value && getData(false)
})

application.allSettled([getData()])
</script>

<template>
  <div class="vip-rebate">
    <div class="tabs">
      <div :style="{ marginBottom: !isTiered ? '16px' : 0 }">
        <div v-if="isTiered && !tabList.length" class="flex justify-between font-semibold">
          <span class="now-receive text-xs mb-2">
            <span>{{ $t('now_wait_receive') }}</span>
            <span class="amount">&nbsp;{{ tieredTotalRebate }}</span>
          </span>
          <span class="cursor-pointer text-sm text-text-white-2 " @click="i18nNavigateTo('/rebate-center/record')">
            {{ $t('vip_rebate_record') }}
          </span>
        </div>
        <template v-if="tabList.length">
          <div class="mb-4 flex items-center text-xs">
            <span class="flex-1 text-text-white-0 font-semibold">{{ $t('type_select') }}</span>
            <span class="cursor-pointer text-text-white-2 font-semibold" @click="i18nNavigateTo('/rebate-center/record')">
              {{ $t('vip_rebate_record') }}
            </span>
          </div>
          <BaseBcTab
            v-model:active-tab="tab"
            :has-bg="false"
            style="--bc-base-tab-height: 2.1875rem;"
            class="mb-4" :tabs="tabList" :has-cloud-img="false"
          />
        </template>
      </div>
      <BaseTable
        v-if="!isTiered"
        class="rebate-table rounded-sm"
        :columns="columns" :data-source="rebateConfig" :loading="APILoading " :skeleton-width="20"
        style="font-size: 0.75rem; color: var(--color-text-white-2);"
        show-out-load
      >
        <template #level="{ record }">
          <div class="center">
            <BaseImage width="1.25rem" :is-network="true" :url="`/images/vip/${record.v}_bc.webp`" />
            <span class="ml-1 text-text-white-0">VIP{{ record.v }}</span>
          </div>
        </template>
        <template #tiered="{ record }">
          <div class="center">
            <span>{{ record.v }}</span>
          </div>
        </template>
      </BaseTable>
      <div v-else>
        <template v-if="APILoading">
          <div class="center">
            <BaseLoading mode="black" />
          </div>
        </template>
        <template v-else-if="tieredRebateValidBetData">
          <div v-for="item in tieredRebateValidBetData" :key="item.platform_id" class="mb-2 bg-bg-black-3 rounded-md py-2 px-4 flex flex-col cursor-pointer text-xs" @click="toDetailPage(item.platform_name, item.game_type)">
            <div class="flex flex-col">
              <div class="flex items-center justify-between">
                <div class="flex">
                  <BaseIcon v-if="item.game_type_icon" :name="item.game_type_icon" />
                  <BaseImage v-else class="icon-bg rounded-sm p-1 pb-0" height="1.5rem" width="1.5rem" fit="contain" :is-network="true" :url="`/images/rebate/${item.platform_id}.webp`" />
                  <div class="main-text mt-auto center ml-1 text-text-white-2 font-semibold">
                    {{ $t('effective_bet') }}<span class="ml-1 mr-2 text-text-white-0">{{ item.valid_bet_amount }}</span>
                    <AppCurrencyIcon style="--tg-app-currency-icon-size:0.875rem;" :currency-type="getCurrencyConfigByCode((item.currency_id))?.name" />
                  </div>
                </div>
                <div class="bg-bg-black-5 center rounded-md size-8">
                  <BaseIcon name="rebate-arrow" class="text-base" />
                </div>
              </div>
              <BaseProcess :percent="Math.floor(item.progressBar)" class="my-2" :show-number="false" />
              <div class="relative text-text-white-2 font-semibold">
                <div v-if=" Number(item.less_valid_bet_amount) > 0" class="flex text-xs">
                  {{ $t('rebet') }} <span class="mx-1 text-text-white-0">{{ item.less_valid_bet_amount }}</span> {{ $t('rebate_recieve1') }}
                  <span class="ml-1 text-text-white-0">{{ item.next_rate }}</span>
                </div>
                <div v-else class="h-2.5 w-1" />
                <div class="flex bg-[rgba(0,0,0,.2)] font-extrabold text-text-white-2 py-2 px-4 rounded-[100px] scale-50 text-xl absolute right-0 origin-right top-[50%] -translate-y-[50%] whitespace-nowrap">
                  <div class="mr-2">
                    {{ $t('rebate_rate1') }}<span class="ml-2 text-text-white-0">{{ item.rate }}</span>
                  </div>
                  <div>{{ $t('rebate_recieve2') }}<span class="ml-2 text-text-white-0">{{ item.rebate_amount }}</span></div>
                </div>
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <BaseEmpty icon="empty-1" />
        </template>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.vip-rebate {
  width: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .rebate-table{
    --tg-table-td-padding-y: 0;
    --tg-table-td-padding-x: 0;
    --tg-table-th-padding-x: 0;
  }
}
</style>
